<%--
  Created by IntelliJ IDEA.
  User: ZHAOHAOTIAN
  Date: 2021/8/4
  Time: 10:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jstl/fmt_rt" prefix="fmt" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <c:import url="../template/_header.jsp"/>
    <title>${resource.title}-知了[团队知识管理应用]</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <link rel="stylesheet" type="text/css" href="../assets/vendor/treeview/bootstrap-treeview.min.css">
</head>

<body>
<div class="re-main">
    <c:import url="../template/_navbar.jsp"/>
    <div class="re-box-6 mt-85">
    <%-- <div style="width: 70%; margin: auto"> --%>
        <div class="container">
            <div class="row">
                <div class="col-3">
                    <div id="tree"></div>
                </div>
                <div class="col-9">
                    <div class="re-box re-box-decorated resource-post">
                        <%-------------------- 资源标题 --------------------%>
                        <div class="resource-post-box">
                            <a id="link-resource-title" class="h3 resource-post-title">${resource.title}</a>
                        </div>
                        <%-------------------- 资源正文 --------------------%>
                        <div id="link-resource-content" class="resource-post-box resource-post-article"></div>
                        <%-------------------- 资源附件 --------------------%>
                        <div id="attachment" class="resource-post-box resource-post-attach re-hide">
                            <div class="font-text-darkgray">附件</div>
                            <div id="file-list"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- START: Footer -->
    <c:import url="../template/_footer.jsp"/>
    <!-- END: Footer -->
</div>
</body>

<!-- START: Scripts -->
<c:import url="../template/_include_js.jsp"/>
<script src="../assets/vendor/treeview/bootstrap-treeview.min.js"></script>
<script language="JavaScript">

    /* jstl replace \n */
    <% request.setAttribute("vEnter", "\n"); %>

    /* global var */
    let bookResourceId = ${resource.id};
    let bookContents = JSON.parse('${fn:replace(resource.contents,vEnter,'')}');

    /* init */
    $(document).ready(function () {
        /* fill right with Book Resource */
        $("#link-resource-content").html('${resource.text}');
        $("#link-resource-title").attr('href', 'javascript:window.open("/resource/resource?id=${resource.id}")');
        fillAttachment(${resource.id});

        /* fill left with Contents Tree */
        $('#tree').treeview({
            data: getTree(),
            enableLinks: true
        });
        setTotalExtra();

        /* init tree view */
        // $('#tree').treeview('collapseAll', {
        //     silent: true
        // });
        $('li.list-group-item').each(function () {
           $(this).css('padding', '8px');
        });
    });

    /* recursively format the tree data */
    let nid = 1;
    function formatTreeData (contents, depth) {
        // console.log(contents);
        for (let i = 0; i < contents.length; i++) {
            /* id */
            contents[i]['nid'] = nid;
            nid += 1;
            /* text */
            totalText[nid - 1] = contents[i]['text'];
            contents[i]['text'] = splitText(contents[i]['text'], 22 - depth * 2);
            /* select */
            if (contents[i]['nodes'] != null) {
                contents[i]['selectable'] = false;
                contents[i]['resource'] = "-1";
                contents[i]['nodes'] = formatTreeData(contents[i]['nodes'], depth + 1);
            } else {
                contents[i]['selectable'] = true;
            }
            /* expand */
            if (depth < 3) {
                contents[i]['state'] = {'expanded': true};
            }
        }
        return contents;
    }

    /* split contents title */
    function splitText(str, maxlen) {
        let retStr = '';
        let len = 0;
        for (let i = 0; i < str.length; i++) {
            /* is EN or CN */
            let c = str.charCodeAt(i);
            if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
                len += 1;
            } else {
                len += 2;
            }
            /* append */
            retStr += str[i];
            /* check length */
            if (len > maxlen) {
                return retStr + '...';
            }
        }
        return retStr;
    }

    /* get tree data */
    let isTreeDataInit = false;
    let totalText = [''];
    function getTree() {
        if (!isTreeDataInit) {
            initTreeData();
            isTreeDataInit = true;
        }
        // console.log(bookContents);
        // console.log(totalText);
        return bookContents;
    }
    function initTreeData() {
        bookContents = formatTreeData(bookContents, 1);
        // add book title to first row of treeView
        bookContents.unshift({'text': '${resource.title}', 'resource': '${resource.id}', 'nid': 0, 'title': true, 'state':{'selected': true}});
        totalText[0] = '${resource.title}';
    }

    /* set total extra label style */
    let titleNodeIds = [];
    function setTotalExtra() {
        let treeData = getTree();
        for (let treeNode of treeData) {
            titleNodeIds.push(treeNode['nid']);
        }
        console.log(titleNodeIds);
        $("li.node-tree").each(function() {
            /* set color */
            let nid = $(this).attr('data-nodeid');
            if (titleNodeIds.indexOf(parseInt(nid)) !== -1 && nid != nowNodeId) {
                $(this).css('background-color', 'rgb(245, 245, 245)');
            }
            /* set total text */
            $(this).attr('title', totalText[nid]);
        })
    }

    /* node click event */
    let nodeId;
    let lastNodeId = 0;
    let nowNodeId = 0;
    let node;
    $(document).on("click","li.node-tree",function(){
        // title
        if ($(this).attr('data-nodeid') === '0') {
            $('#tree').treeview('selectNode', [ 0, { silent: false } ]);
            setPadding();
            window.location.href = '/resource/resource?id=${resource.id}';
            return;
        }
        // keep padding
        setPadding();
        // keep title grey color
        setTotalExtra();
        // fill resource
        node = $('#tree').treeview('getSelected', nodeId);
        if (node[0] == null) {
            return;
        }
        nowNodeId = node[0]['nodeId'];
        if (nowNodeId !== lastNodeId && node[0] != null){
            lastNodeId = nowNodeId;
            fillResource(node[0]['resource']);
        }
    });

    /* fill resource by ID*/
    function fillResource(id) {
        $.ajax({
            type: "get",
            url: "/bookResource/linkResource",
            data: {
                id: id
            },
            success: function (data) {
                console.log(data);
                if (id == ${resource.id}) {
                    $("#link-resource-title").attr('href', 'javascript:window.open("/resource/resource?id=' + id + '")');
                } else {
                    $("#link-resource-title").attr('href', '/resource/resource?id=' + id);
                }

                $("#link-resource-title").html(data['resource']['title']);
                $("#link-resource-title").attr('href', 'javascript:window.open("/resource/resource?id=' + id + '")');
                $("#link-resource-content").html(data['resource']['text']);

                // attachment
                fillAttachment(id);
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '资源获取失败！'});
            }
        });
    }

    /* fill attachment by id */
    function fillAttachment(id) {
        $("#attachment").addClass('re-hide');
        $.ajax({
            type: "get",
            url: "/bookResource/linkAttachment",
            data: {
                id: id
            },
            success: function (data) {
                // attachment
                let attachment = JSON.parse(data['attachment']);
                if (attachment.length !== 0) {
                    let htmlStr = '';
                    for (let i = 0; i < attachment.length; i++) {
                        // 支持“新文件下载接口”的同时，需要兼容旧“nfs下载”！
                        var url = attachment[i].url;
                        if (url.indexOf("/util/downloadAttachment") != -1) {
                            htmlStr += "<div id=\"atta" + attachment[i].id + "\" class=\"mnt-7 font-text\"><a>" + attachment[i].name + "&nbsp;</a>&nbsp;&nbsp;<a href=\"" + attachment[i].url + "&name=" + attachment[i].name + "\">[下载]</a></div>";
                        } else {
                            htmlStr += "<div id=\"atta" + attachment[i].id + "\" class=\"mnt-7 font-text\"><a>" + attachment[i].name + "&nbsp;</a>&nbsp;&nbsp;<a href=\"" + attachment[i].url + "?flag=download&&attname=" + attachment[i].name + "\">[下载]</a></div>";
                        }
                    }
                    $("#file-list").html(htmlStr);
                    $("#attachment").removeClass('re-hide');
                } else {
                    $("#file-list").html('');
                }
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '拉取资源附件失败！'});
            }
        });
    }

    /* keep padding (to avoid refresh treeview) */
    function setPadding () {
        $('li.list-group-item').each(function () {
            $(this).css('padding', '8px');
        });
    }

    /* get url param (replace by JSTL) */
    function getQueryVariable(variable)
    {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0; i<vars.length; i++) {
            var pair = vars[i].split("=");
            if(pair[0] == variable){return pair[1];}
        }
        return(false);
    }

    /* a test
    function getTreeTest() {
        let data = [{
            text: "测试主",
            selectable: false,
            resource: "-1",
            nodes: [{
                text: "周报",
                resource: "-1",
                selectable: false,
                nodes: [{
                    text: "0802",
                    selectable: true,
                    resource: "17472"
                }, {
                    text: "0726",
                    selectable: true,
                    resource: "17465"
                }]
            }, {
                text: "cssTest",
                selectable: true,
                resource: "17460"
            }]
        }, {
            text: "测试标题一",
            selectable: true,
            resource: "17434"
        }, {
            text: "测试标题二",
            selectable: true,
            resource: "17434"
        }, {
            text: "测试标题三",
            selectable: true,
            resource: "17434"
        }, {
            text: "测试标题四",
            selectable: true,
            resource: "17434"
        }];
        return data;
    };*/

</script>
<!-- END: Scripts -->

</html>